<template>
  <view class="app-layout">
    <!-- <app-header></app-header> -->
    <view class="app-main">
      <app-sider pageKey="products"></app-sider>
      <view class="menu-con">
        <view class="menu-bar">
          <view v-for="(tab, index) in tabList" :key="index" class="menu-item" :class="{ active: currentTab == index }"
            @click="handlecurrentTab(index)">
            <view>
              <image style="width: 56px; height: 56px" mode="widthFix"
                :src="currentTab === index ? tab.icon_ : tab.icon"></image>
            </view>
            <view>{{ tab.name }}</view>
          </view>
        </view>
      </view>

      <view class="app-content">
        <template v-if="currentTab == 0">
          <view class="tabs-wrapper">
            <u-tabs :list="tabListAll" @click="tabClick1" :scrollable="true" keyName="name"
              :activeStyle="{ color: '#0F90FD', fontWeight: '500', fontSize: '16px' }">
              <template #content="{ item, keyName, index }">
                <view style="position: relative">
                  {{ item[keyName] }}
                  <u-badge type="error" max="99" :value="item.num" :absolute="true"
                    :offset="getOffset(item.num)"></u-badge>
                </view>
              </template>
            </u-tabs>
          </view>
          <view class="order-search">
            <view v-for="(tab, index) in tabType" :key="index" class="type-item"
              :class="{ activeType: currentTabType == index }" @click="handlecurrentTabType(index)">
              {{ tab }}
            </view>
            <u-search placeholder="请输入商品ID/名称" v-model="pageInfo.keyword" clearable bgColor="#fff" borderColor="#e5e5e5"
              :showAction="false" @search="handleSearch" @clear="handleReset"></u-search>

            <view class="flex-row" style="flex: 1">
              <u-button type="primary" text="搜索" @click="handleSearch"></u-button>
              <u-button :plain="true" text="重置" @click="handleReset"></u-button>
            </view>
          </view>
        </template>
        <view class="goods-wrapper" v-if="currentTab == 0">
          <view class="goods-left">
            <scroll-view scroll-y="true" ref="scrollView" style="height: 100%; width: 100%">
              <view class="category-list">
                <!-- 递归渲染分类项 -->
                <template v-for="(item, index) in range" :key="item.categoryId">
                  <view class="category-item" :style="{ paddingLeft: `${item.level * 10}px` }"
                    :class="{ activeItem: currentSelectedId == item.categoryId }" @click="handleItemClick(item)">
                    <!-- 内容区：名称 + 数量 -->
                    <view class="item-content">
                      <text class="category-name">{{ item.categoryName }}</text>
                      <text class="item-count" v-if="item.children && item.children.length">
                        ({{ item.children.length }})
                      </text>
                    </view>

                    <!-- 箭头按钮（有子分类时显示） -->
                    <view class="expand-arrow" v-if="item.children && item.children.length"
                      @click.stop="toggleExpand(item)">
                      <u-icon name="arrow-right" v-if="!item.isExpanded"
                        :color="currentSelectedId == item.categoryId ? '#0F90FD' : ''"></u-icon>
                      <u-icon name="arrow-down" v-if="item.isExpanded"
                        :color="currentSelectedId == item.categoryId ? '#0F90FD' : ''"></u-icon>
                    </view>
                  </view>

                  <!-- 递归渲染子分类（仅当展开时显示） -->
                  <template v-if="item.isExpanded && item.children && item.children.length">
                    <view v-for="(child, childIdx) in item.children" :key="child.categoryId" class="category-item"
                      :class="{ activeItem: currentSelectedId === child.categoryId }"
                      :style="{ paddingLeft: `${child.level * 10}px` }" @click="handleItemClick(child)">
                      <!-- 内容区：名称 + 子分类数量 -->
                      <view class="item-content">
                        <text class="category-name">{{ child.categoryName }}</text>
                        <text class="item-count" v-if="child.children && child.children.length">
                          ({{ child.children.length }})
                        </text>
                      </view>

                      <!-- 箭头按钮（有子分类时显示） -->
                      <view class="expand-arrow" v-if="child.children && child.children.length"
                        @click.stop="toggleExpand(child)">
                        <u-icon name="arrow-right"
                          :color="currentSelectedId == child.categoryId ? '#0F90FD' : ''"></u-icon>
                      </view>
                    </view>
                  </template>
                </template>
              </view>
            </scroll-view>
          </view>
          <view class="goods-list-wrapper">
            <view class="" style="margin: 10px 0; flex: 1; overflow: hidden;">
              <scroll-view scroll-y="true" ref="scrollView" style="height: 100%" @scrolltolower="onScrollToLower"
                v-if="goodsList.length > 0">
                <u-checkbox-group v-model="checked" style="width: 30px" @change="checkClick">
                  <view class="goods-grid">
                    <view class="goods-item" v-for="(item, index) in goodsList" :key="index" @click="handelEdit(item)">
                      <view class="status-tag" :class="{
                          'off-sale': item.isPublished === 0,
                          'on-sale': item.isPublished === 1,
                        }">
                        {{ item.isPublished === 0 ? '下架' : '在售' }}
                      </view>

                      <u-checkbox activeColor="#0F90FD" shape="circle" label="" :name="item.spuId"
                        v-if="btnShow"></u-checkbox>

                      <view class="sold-out-mask" v-if="item.totalStock === 0">
                        <image src="../../static/imgs/sell.png" mode="scaleToFill"></image>
                      </view>

                      <image class="goods-img" :src="item.mainImage" mode="aspectFill" @error="onImageError"></image>

                      <view class="goods-info">
                        <view class="goods-infoi-top">
                          <text class="goods-name">{{ item.name }}</text>
                          <text class="goods-type">限量</text>
                        </view>
                        <view class="stock-price">
                          <text class="stock"> 库存{{ item.totalStock }} </text>
                          <text class="price">¥{{ item.lowestPrice }}</text>
                        </view>
                      </view>
                    </view>
                  </view>
                </u-checkbox-group>
              </scroll-view>
              <!--    <view class="" style="height: 57vh; text-align: center; line-height: 50px" v-else>
                暂无数据
              </view> -->
              <view class="empty-box" style="text-align: center;padding-top: 5vh;">
                <image src="/src/static/imgs/emptyW.png" mode="widthFix" style="width: 240px;"></image>
                <view class="text1" style="color: #999;">暂无数据</view>
              </view>
            </view>
            <view class="detail-foot" v-if="!btnShow">
              <view class="foot-btn" style="margin: auto">
                <view class="order-btn" @click="handleAdd">新增商品</view>
                <view class="order-btn1" @click="bulkOperation">批量操作</view>
              </view>
            </view>
            <view class="detail-foot" v-if="btnShow">
              <view class="foot-info">
                <u-checkbox-group v-model="checkAll" @change="checkAllClick">
                  <u-checkbox activeColor="#0F90FD" label="全选" name="all"></u-checkbox>
                </u-checkbox-group>
              </view>
              <view class="foot-btn">
                <view class="order-btn" @click="handelPrice" style="padding: 7px 26px">改价格</view>
                <view class="order-btn" style="padding: 7px 26px" @click="handelSettings">库存配置</view>
                <view class="order-btn" style="padding: 7px 26px" @click="handleInventory">库存调整</view>
                <view class="order-btn" @click="handleDelete" style="padding: 7px 26px">删除</view>
                <view class="order-btn" @click="handleGrounding" style="padding: 7px 26px">上架</view>
                <view class="order-btn" @click="handleGroundingNo" style="padding: 7px 26px;margin-right:0">下架</view>
              </view>
            </view>
          </view>
        </view>
        <classification v-if="currentTab == 1" :key="componentKey" ref="classificationRef" class="class-comp" />
        <feeding v-if="currentTab == 2" :key="componentKey" ref="feedingRef"
          style="display: flex; flex-direction: column;flex: 1; overflow: hidden;" />
        <attribute v-if="currentTab == 3" :key="componentKey" ref="attributeRef"
          style="display: flex; flex-direction: column; flex: 1;overflow: hidden;" />
        <view class="floating-button" v-if="btnShow" @click="closeEdit">
          <view class="">
            <image src="../../static/imgs/back.png" mode=""></image>
            <text>取消编辑</text>
          </view>
        </view>
      </view>
    </view>
  </view>
  <u-popup :show="show" @close="popupCancel" :round="10" mode="center">
    <view class="popup-cons">
      <view class="applyfor-tit">
        {{ showTitle }}
      </view>
      <view class="applyfor-info">
        {{ showInfo }}
      </view>
      <view class="button-group">
        <button class="cancel-btn" @click="popupCancel">取消</button>
        <button class="pay-btn" @click="popupSure">确认</button>
      </view>
    </view>
  </u-popup>
  <u-popup :show="showSure" @close="popupSures" :round="10" mode="center">
    <view class="popup-cons" style="width: 330px">
      <template v-if="showStatus == 0">
        <view class="applyfor-image">
          <image src="../../static/imgs/success.png" mode=""></image>
        </view>
        <view class="applyfor-green">
          {{ showTitle }}
        </view>
      </template>
      <template v-if="showStatus == 1 || showStatus == 2">
        <view class="applyfor-image">
          <image src="../../static/imgs/fill.png" mode=""></image>
        </view>
        <view class="applyfor-green" style="color: #ff8700">
          {{ showTitle }}
        </view>
      </template>
      <view class="applyfor-info">
        {{ showInfo }}
      </view>
      <view class="button-group" style="margin-top: 18rpx">
        <button class="pay-btn" @click="popupSures">确认</button>
      </view>
    </view>
  </u-popup>
</template>
<script setup>
  import feeding from './feeding/index.vue'
  import classification from './classification/index.vue'
  import attribute from './attribute/index.vue'
  import {
    ref,
    computed,
    nextTick,
    reactive,
  } from 'vue'
  import {
    onLoad,
    onShow
  } from '@dcloudio/uni-app'
  import {
    getTreeCategory,
    productPage,
    deleteProducts,
    updatePublish,
    productPageCount
  } from '@/requests/apis/products'
  import {
    useSysInfo
  } from '@/stores/modules/sysInfo'
  const {
    safeAreaBottom
  } = useSysInfo()
  console.log(safeAreaBottom, 'safeAreaBottom1111 ')
  let scrollTop = ref()
  let goodsScroll = ref(null)
  let show = ref(false)
  let showSure = ref(false)
  let showType = ref()
  let showTitle = ref()
  let showStatus = ref(0)
  let showInfo = ref()
  let checked = ref([])
  let checkAll = ref()
  let isFash = ref(false)
  let currentSelectedId = ref(-1)
  let classificationRef = ref(null)
  let feedingRef = ref(null)
  let attributeRef = ref(null)
  let currentTab = ref(0)
  let currentTabType = ref(0)
  // let tabList = ref(['商品管理', '商品分类', '商品加料', '商品属性'])
  let tabList = ref([
    {
      name:"商品管理",
      icon: '/static/icons/icon9.png',
      icon_: '/static/icons/icon9_.png',
    },
    {
      name:"商品分类",
      icon: '/static/icons/icon10.png',
      icon_: '/static/icons/icon10_.png',
    },
    {
      name:"商品加料",
      icon: '/static/icons/icon11.png',
      icon_: '/static/icons/icon11_.png',
    },
    {
      name:"商品属性",
      icon: '/static/icons/icon12.png',
      icon_: '/static/icons/icon12_.png',
    },
  ])
  let tabType = ref(['全部', '门店自提', '外卖配送'])
  let range = ref([])
  let btnShow = ref(false)
  let componentKey = ref(0)
  let pageInfo = reactive({
    total: 0,
    page: 1,
    limit: 20,
    keyword: '',
    status: undefined,
    sceneCode: undefined,
    categoryIds: undefined
  });
  const tabListAll = ref([{
      name: '全部',
      num: 0,
    },
    {
      name: '在售',
      num: 0,
    },
    {
      name: '下架',
      num: 0,
    },
    {
      name: '售空',
      num: 0,
    },
  ])
  const goodsList = ref([])
  let isMergeRequest = false;
  const bottomInset = ref(0);
  onLoad(() => {
    // getCategoryList()
  })
  onShow(async () => {
    // #ifdef APP-PLUS
    uni.hideTabBar()
    // #endif
    // btnShow.value = false
    // pageInfo.keyword = ''
    // pageInfo.status = undefined
    // pageInfo.sceneCode = undefined
    pageInfo.categoryIds = undefined
    checked.value = []
    checkAll.value = undefined
    // currentTabType.value = 0
    currentSelectedId.value = -1
    getMerge()
    // currentTab.value = 0
    getCategoryList()
    if (currentTab.value === 1) {
      currentTab.value = 0;
      await nextTick();
      currentTab.value = 1;
      await nextTick();
      componentKey.value++;
    } else if (currentTab.value === 2) {
      currentTab.value = 0;
      await nextTick();
      currentTab.value = 2;
      await nextTick();
      componentKey.value++;
    } else if (currentTab.value === 3) {
      currentTab.value = 0;
      await nextTick();
      currentTab.value = 3;
      await nextTick();
      componentKey.value++;
    }
  })
  const getMerge = () => {
    const prevPage = pageInfo.page;
    if (prevPage !== 1) {
      isMergeRequest = true;
      pageInfo.limit = prevPage * 20;
      pageInfo.page = 1;
      getproductPage('merge');
    } else {
      pageInfo.page = 1;
      pageInfo.limit = 20;
      getproductPage();
    }
  };
  let oldTop = ref(0)
  const scroll = (e) => {
    oldTop.value = e.detail.scrollTop
  }
  const onScrollToLower = (e) => {
    if (pageInfo.page * pageInfo.limit < pageInfo.total && goodsList.value.length >= 20) {
      pageInfo.page++;
      getproductPage('add');
    }
  }
  const getOffset = (num) => {
    const str = (num || 0).toString();
    const len = str.length;
    // 根据字符长度返回不同的offset值
    if (len === 1) {
      return [-10, -15]; // 1位数字的偏移
    } else if (len === 2) {
      return [-10, -25]; // 2位数字的偏移
    } else {
      return [-10, -30]; // 3位及以上数字的偏移
    }
  };
  const getPageCount = async () => {
    let res = await productPageCount()
    tabListAll.value[0].num = res.Result.totalCount
    tabListAll.value[1].num = res.Result.onSaleCount
    tabListAll.value[2].num = res.Result.unPublishCount
    tabListAll.value[3].num = res.Result.soldOutCount
    console.log(res, '1111111111')
  }
  const getproductPage = async (type) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    try {
      let res = await productPage({
        ...pageInfo,
      })
      pageInfo.total = res.Result.total
      if (type === 'merge') {
        goodsList.value = res.Result.records || [];
        pageInfo.page = Math.ceil(goodsList.value.length / 20);
        pageInfo.limit = 20;
        isMergeRequest = false;
      } else if (type === 'add') {
        goodsList.value = [...goodsList.value, ...(res.Result.records || [])];
      } else {
        goodsList.value = res.Result.records || [];
      }

      getPageCount()
    } catch (error) {
      console.log(error);
      uni.hideLoading();
    } finally {
      uni.hideLoading();
    }

  }
  const allChecked = computed({
    get() {
      return goodsList.value.every((item) => item.checked)
    },
    set(newVal) {
      goodsList.value.forEach((item) => {
        item.checked = newVal
      })
    },
  })
  const getCategoryList = async () => {
    let res = await getTreeCategory({
      isActive: 1
    })
    let arr = res.Result || []
    arr.unshift({
      categoryName: '全部',
      categoryId: -1,
      level: 1,
      children: [],
    })
    range.value = initCategoryData(arr)
  }
  // 初始化分类数据：添加展开状态和层级标识
  const initCategoryData = (list, level = 1) => {
    return list.map((item) => {
      // 将每个分类项转换为响应式对象，并添加状态
      const reactiveItem = reactive({
        ...item, // 保留原始数据
        isExpanded: false, // 控制展开/收起
        level: level, // 控制缩进层级
      })
      // 递归处理子分类
      if (reactiveItem.children && reactiveItem.children.length) {
        reactiveItem.children = initCategoryData(reactiveItem.children, level + 1)
      }
      return reactiveItem
    })
  }
  // 切换展开/收起状态
  const toggleExpand = (item) => {
    console.log(item, '111')
    item.isExpanded = !item.isExpanded
  }
  const handleSearch = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    getproductPage()
  }
  const handleReset = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    pageInfo.keyword = ''
    getproductPage()
  }
  // 递归收集某个分类下所有子级（含后代）的categoryId
  const collectAllChildIds = (category) => {
    let ids = [];
    if (category.children && category.children.length > 0) {
      category.children.forEach(child => {
        ids.push(child.categoryId);
        ids = [...ids, ...collectAllChildIds(child)];
      });
    }
    return ids;
  };
  // 点击分类项（可选：处理选中逻辑）
  const handleItemClick = (item) => {
    currentSelectedId.value = item.categoryId;
    if (item.categoryId == -1) {
      pageInfo.categoryIds = undefined
    } else {
      if (item.level === 1) {
        const allChildIds = collectAllChildIds(item);
        const targetIds = allChildIds.length > 0 ?
          allChildIds : [item.categoryId];
        console.log('目标ID集合：', targetIds);
        pageInfo.categoryIds = targetIds
      } else {
        console.log(item.categoryId)
        pageInfo.categoryIds = [item.categoryId]

      }
    }
    pageInfo.limit = 20;
    pageInfo.page = 1;
    getproductPage()
    // scrollTop.value = oldTop.value;
    setTimeout(() => {
      scrollTop.value = 0;
    }, 50);
  };
  // 切换
  const handlecurrentTab = async (index) => {
    console.log(index, 'iniinininiiiiiiii')
    currentTab.value = index
    btnShow.value = false
    pageInfo.status = undefined;
    getCategoryList()
    if (index == 0) {
      getproductPage();
    }
  }
  const handlecurrentTabType = (index) => {
    console.log(index, 'index')
    if (index == 1) {
      pageInfo.sceneCode = 'pickup'
    } else if (index == 2) {
      pageInfo.sceneCode = 'takeout'
    } else {
      pageInfo.sceneCode = undefined
    }
    pageInfo.limit = 20;
    pageInfo.page = 1;
    currentTabType.value = index
    getproductPage()
    scrollTop.value = oldTop.value;
    setTimeout(() => {
      scrollTop.value = 0;
    }, 50);
  }
  const tabClick1 = (e) => {
    let obj = {
      "全部": undefined,
      '在售': 0,
      '下架': 1,
      '售空': 2,
    };
    pageInfo.status = obj[e.name];
    pageInfo.limit = 20;
    pageInfo.page = 1;

    getproductPage();

    scrollTop.value = oldTop.value;
    setTimeout(() => {
      scrollTop.value = 0;
    }, 50);
  };


  // 取消编辑
  const closeEdit = () => {
    checked.value = []
    btnShow.value = false
  }
  // 新增商品
  const handleAdd = () => {
    uni.navigateTo({
      url: '/pages/products/formAdd',
    })
  }
  // 批量
  const bulkOperation = () => {
    btnShow.value = true
  }
  // 删除
  const handleDelete = () => {
    if (checked.value.length <= 0) {
      uni.showToast({
        title: `请先选择商品`,
        icon: 'none',
      })
      return
    }
    show.value = true;
    showType.value = 1;
    showTitle.value = '确认删除'
    showInfo.value = '是否确认删除所选商品，删除后商品不可恢复。'
  }
  // 弹窗取消
  const popupCancel = () => {
    show.value = false
  }
  // 弹窗确认
  const popupSure = () => {
    show.value = false
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    // 删除
    if (showType.value == 1) {
      setTimeout(() => {
        deleteProducts({
          spuIds: checked.value
        }).then((res) => {
          showSure.value = true
          if (res.ResponseCode == 1) {
            showInfo.value = `${checked.value.length}个商品已成功删除！`
            showTitle.value = '删除成功'
            showStatus.value = 0
            pageInfo.page = 1
            pageInfo.limit = 20
            checked.value = []
            getMerge()
          }
        })
        uni.hideLoading()
      }, 800)
    } else if (showType.value == 2) {
      const data = goodsList.value
        .filter(item => checked.value.includes(item.spuId))
        .map(item => JSON.parse(JSON.stringify(item)));

      data.forEach(ite => {
        ite.isPublished = 1;
      });
      setTimeout(() => {
        updatePublish({
          productList: data
        }).then((res) => {
          showSure.value = true
          if (res.ResponseCode == 1) {
            showInfo.value = `${checked.value.length}个商品已成功上架！`
            showTitle.value = '上架成功'
            showStatus.value = 0
            pageInfo.page = 1
            pageInfo.limit = 20
            checked.value = []
            getMerge()
          }
        })
        uni.hideLoading()
      }, 800)
    } else if (showType.value == 3) {
      const data = goodsList.value
        .filter(item => checked.value.includes(item.spuId))
        .map(item => JSON.parse(JSON.stringify(item)));

      data.forEach(ite => {
        ite.isPublished = 0;
      });
      setTimeout(() => {
        updatePublish({
          productList: data
        }).then((res) => {
          showSure.value = true
          if (res.ResponseCode == 1) {
            showInfo.value = `${checked.value.length}个商品已成功下架！`
            showTitle.value = '下架成功'
            showStatus.value = 0
            pageInfo.page = 1
            pageInfo.limit = 20
            checked.value = []
            getMerge()
          }
        })
        uni.hideLoading()
      }, 800)
    }
  }
  //二级弹窗确认
  const popupSures = () => {
    showSure.value = false;
  }
  // 上架
  const handleGrounding = () => {
    console.log(checked.value, goodsList.value)
    if (checked.value.length <= 0) {
      uni.showToast({
        title: `请先选择商品`,
        icon: 'none',
      })
      return
    }
    // 判断出已上架的数据
    const invalidGoods = goodsList.value.filter(item =>
      checked.value.includes(item.spuId) && item.isPublished == 1
    );
    if (invalidGoods.length > 0) {
      const names = invalidGoods.map(item => `[${item.name}]`); // 包裹名称为 [xxx]
      let displayNames = '';
      if (names.length <= 3) {
        displayNames = names.join('、');
      } else {
        displayNames = `${names.slice(0, 3).join('、')}等`;
      }
      const tip = `${displayNames}商品已是上架状态，无需上架！`;
      showSure.value = true
      showStatus.value = 1
      showInfo.value = tip
      showTitle.value = '上架异常'
      return;
    }
    show.value = true;
    showType.value = 2;
    showTitle.value = '确认上架'
    showInfo.value = '是否确认上架所选商品，上架后商品将可售。'
  }
  const handleGroundingNo = () => {
    console.log(checked.value, goodsList.value)
    // 1. 筛选：下架状态
    const invalidGoods = goodsList.value.filter(item =>
      checked.value.includes(item.spuId) && item.isPublished == 0
    );
    const data = goodsList.value.filter(item =>
      checked.value.includes(item.spuId)
    );
    if (invalidGoods.length > 0) {
      const names = invalidGoods.map(item => `[${item.name}]`); // 包裹名称为 [xxx]
      let displayNames = '';
      if (names.length <= 3) {
        displayNames = names.join('、');
      } else {
        displayNames = `${names.slice(0, 3).join('、')}等`;
      }

      const tip = `${displayNames}商品已是下架状态，无需下架！`;
      showSure.value = true
      showStatus.value = 2
      showInfo.value = tip
      showTitle.value = '下架异常'
      return;
    }
    show.value = true;
    showType.value = 3;
    showTitle.value = '确认下架'
    showInfo.value = '是否确认下架所选商品，下架后商品不可售。'
  }
  const checkAllClick = (ev) => {
    if (!ev.length) {
      checked.value = []
    } else {
      checked.value = goodsList.value.map((item) => {
        return item.spuId
      })
    }
  }
  const checkClick = (ev) => {
    if (ev.length === goodsList.value.length) {
      checkAll.value = ['all']
    } else {
      checkAll.value = []
    }
  }
  // 编辑
  const handelEdit = (item) => {
    if (btnShow.value) {
      const spuId = item.spuId;
      const index = checked.value.indexOf(spuId);

      if (index === -1) {
        checked.value.push(spuId);
      } else {
        checked.value.splice(index, 1);
      }
    } else {
      uni.navigateTo({
        url: `/pages/products/formAdd?spuId=${item.spuId}`,
      })
    }

  }

  // 改价格
  const handelPrice = () => {
    if (checked.value.length <= 0) {
      uni.showToast({
        title: `请先选择商品`,
        icon: 'none',
      })
      return
    }

    uni.navigateTo({
      url: `/pages/products/priceAdjustment?spuIds=${checked.value}`,
    })

  }
  // 库存调整
  const handleInventory = () => {
    if (checked.value.length <= 0) {
      uni.showToast({
        title: `请先选择商品`,
        icon: 'none',
      })
      return
    }
    uni.navigateTo({
      url: `/pages/products/inventory?spuIds=${checked.value}`,
    })
  }
  // 库存设置
  const handelSettings = () => {
    if (checked.value.length <= 0) {
      uni.showToast({
        title: `请先选择商品`,
        icon: 'none',
      })
      return
    }
    uni.navigateTo({
      url: `/pages/products/settings?spuIds=${checked.value}`,
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.u-tag) {
    padding: 0 5px !important;
  }

  :deep(.u-checkbox) {
    z-index: 999 !important;
  }

  .floating-button {
    position: fixed;
    bottom: 100px;
    right: 20px;

    view {
      width: 60px;
      height: 60px;
      background: #000000;
      border-radius: 26px;
      opacity: 0.65;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    text {
      font-weight: 500;
      font-size: 12px;
      color: #ffffff;
    }

    image {
      width: 22px;
      height: 20px;
    }
  }

  .tabs-wrapper {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
    height: 44px;
    background: #fff;
    margin: 10px;

    :deep(.u-tabs) {
      width: 100% !important;

      .u-tabs__wrapper__nav__item {
        flex: 1 !important;
      }

      .u-tabs__wrapper__nav__item__text {
        white-space: nowrap;
      }
    }
  }

  .order-search {
    display: flex;
    background-color: #fff;
    margin: 0px 10px 0;
    padding: 12px 145px 12px 20px;
    box-sizing: border-box;

    .type-item {
      font-weight: 400;
      font-size: 14px;
      color: #666666;
      display: flex;
      align-items: center;
      background: #f6f6f6;
      padding: 7px 12px;
      box-sizing: border-box;
      border-radius: 10px;
      margin-right: 10px;
    }

    .activeType {
      background: rgba(15, 144, 253, 0.1);
      color: #0f90fd;
    }

    :deep(button) {
      width: 74px;
      height: 38px;
      margin-left: 11px;
      margin-right: 0;
      border-radius: 100px;
    }

    :deep(.uni-date) {
      margin-right: 10px;
    }

    :deep(.uni-date-x--border) {
      border-radius: 100px !important;
    }

    :deep(.uni-date-x) {
      border-radius: 100px !important;
    }
  }

  .goods-wrapper {
    display: flex;
    flex: 1;
    overflow: hidden;

    .goods-left {
      margin: 10px;
      background-color: #fff;
      border-radius: 8px;
      height: 100%;
      padding-top: 11px;
      padding-bottom: 20px;
      box-sizing: border-box;
      width: 23%;
    }

    .category-list {
      .category-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 40px;
        margin: 0px 10px;
        border-radius: 10px;
        padding: 0 10px;
        box-sizing: border-box;
        font-weight: 500;
        font-size: 14px;
        color: #666666;

        &.activeItem {
          background: rgba(15, 144, 253, 0.1);
          color: #0f90fd !important;
        }
      }

      .item-content {
        display: flex;
        align-items: center;
      }

      .item-count {
        margin-left: 8px;
      }

      .expand-arrow {}
    }

    .goods-list-wrapper {
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      :deep(.u-checkbox-group) {
        width: 100% !important;
      }

      .goods-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        box-sizing: border-box;
        width: 100%;
      }

      /* 单个商品项 */
      .goods-item {
        flex: 0 0 calc(25% - 12px);
        box-sizing: border-box;
        position: relative;
        border-radius: 8px;
        background-color: #fff;
        overflow: hidden;

        :deep(.u-checkbox) {
          position: absolute;
          top: 0;
          right: 0;
        }

        /* 状态标签 */
        .status-tag {
          position: absolute;
          top: 0;
          left: 0;
          padding: 2px 10px;
          border-radius: 10px 0px 10px 0px;
          color: #fff;
          font-weight: 500;
          font-size: 12px;
          color: #ffffff;
          line-height: 17px;
          z-index: 2;

          &.off-sale {
            background: #f32f1d;
          }

          &.on-sale {
            background: #52c41a;
          }
        }

        /* 售罄遮罩 */
        .sold-out-mask {
          position: absolute;
          top: 40px;
          left: 0;
          width: 100%;
          // height: calc(100% - 70px);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 1;

          image {
            width: 108px;
            height: 108px;
          }
        }

        /* 单选框 */
        .item-check {
          position: absolute;
          top: 10px;
          right: 10px;
          z-index: 3; // 确保在最上层
        }

        /* 商品图片 */
        .goods-img {
          width: 100%;
          height: 160px;
        }

        /* 底部信息区 */
        .goods-info {
          text-align: left;
          padding: 10px;

          .goods-infoi-top {
            display: flex;
            justify-content: space-between;

            .goods-name {
              flex: 1;
              font-weight: 500;
              font-size: 14px;
              color: #333333;
              display: block;
              /* 新增：文本溢出处理 */
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .goods-type {
              min-width: 40px;
              position: relative;
              display: inline-block;
              padding: 2px 7px 2px 7px;
              box-sizing: border-box;
              background-color: #5f93f8;
              color: #ffffff;
              font-size: 12px;
              border-radius: 0 4px 4px 0;

              &::after {
                content: '';
                position: absolute;
                top: 0;
                left: -8px;
                width: 0;
                height: 0;
                border-top: 10px solid transparent;
                border-bottom: 10px solid transparent;
                border-right: 8px solid #5f93f8;
              }
            }
          }

          .stock-price {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .stock {
              font-size: 12px;
              color: #0f90fd;
            }

            .price {
              font-size: 14px;
              color: #ff6600;
            }
          }
        }
      }

      .detail-foot {
        margin-top: auto;
        position: static;
        bottom: 0;
        // width: 71vw;
        background: #ffffff;
        box-shadow: 0px -2px 4px 0px rgba(51, 70, 129, 0.1);
        border-radius: 10px;
        height: 54px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 10px 0 20px;
        box-sizing: border-box;
      }
    }
  }

  .class-comp {
    display: flex;
    width: 100%;
    flex: 1;
    flex-direction: column;
  }
</style>
